﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.VisualBasic;
using Microsoft.VisualBasic.FileIO;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Net;
using webapi.DTO;
using webapi.Helper;
using webapi.Model;

namespace webapi.Controllers
{
    [ApiController]
    [Route("[controller]")]
    [Authorize]
    public class AdminController : ControllerBase
    {
        private readonly ILogger<AdminController> _logger;

        private DbContextHelper _dbContextHelper;

        private HashHelper _hashHelper;

        private FileHelper _fileHelper;
        public enum StatusEnum
        {
            UnPaid,
            Undelivered,
            Delivered,
            Completed,
            Processing,
            Returned,
            Deleted
        }

        public AdminController(ILogger<AdminController> logger, DbContextHelper dbContextHelper)
        {
            _logger = logger;
            _dbContextHelper = dbContextHelper;
            _hashHelper = new HashHelper();
            _fileHelper = new FileHelper();
        }

        [HttpPost("GetUserListAdmin")]
        [Authorize]
        public AdminGetUserOutput GetUserListAdmin([FromBody] AdminGetUserInput input)
        {
            var userClaim = HttpContext.User.Claims;
            var userGuid = userClaim.FirstOrDefault(c => c.Type == "UserGuid")?.Value;
            var userGroupId = userClaim.FirstOrDefault(c => c.Type == "UserGroupId")?.Value;
            if (userGroupId == "0")
            {
                return new AdminGetUserOutput()
                {
                    error_code = "2002",
                    status = "200",
                    msg = "Unauthorized",
                };
            }
            int listCount = 0;
            List<AdminUser> users = new List<AdminUser>();
            List<UserInfoModel> usersInfo = new List<UserInfoModel>();

            if (!string.IsNullOrWhiteSpace(input.keyword))
            {
                if (input.filter == "-1")
                {
                    listCount = _dbContextHelper.UserInfo.Where(p => p.DELETE_DATE == null).Where(p => p.EMAIL_ADDRESS.ToLower().Contains(input.keyword.ToLower()) || p.NICKNAME.ToLower().Contains(input.keyword.ToLower())).Count();
                    usersInfo = _dbContextHelper.UserInfo.Where(p => p.DELETE_DATE == null).Where(p => p.EMAIL_ADDRESS.ToLower().Contains(input.keyword.ToLower()) || p.NICKNAME.ToLower().Contains(input.keyword.ToLower())).Skip(input.pageNum * (input.pageNum - 1)).Take(input.pageSize).ToList();
                }
                else
                {
                    listCount = _dbContextHelper.UserInfo.Where(p => p.DELETE_DATE != null).Where(p => p.EMAIL_ADDRESS.ToLower().Contains(input.keyword.ToLower()) || p.NICKNAME.ToLower().Contains(input.keyword.ToLower())).Count();
                    usersInfo = _dbContextHelper.UserInfo.Where(p => p.DELETE_DATE != null).Where(p => p.EMAIL_ADDRESS.ToLower().Contains(input.keyword.ToLower()) || p.NICKNAME.ToLower().Contains(input.keyword.ToLower())).Skip(input.pageNum * (input.pageNum - 1)).Take(input.pageSize).ToList();
                }
            }
            else
            {
                if (input.filter == "-1")
                {
                    listCount = _dbContextHelper.UserInfo.Where(p => p.DELETE_DATE == null).Count();
                    usersInfo = _dbContextHelper.UserInfo.Where(p => p.DELETE_DATE == null).Skip(input.pageNum * (input.pageNum - 1)).Take(input.pageSize).ToList();
                }
                else
                {
                    listCount = _dbContextHelper.UserInfo.Where(p => p.DELETE_DATE != null).Count();
                    usersInfo = _dbContextHelper.UserInfo.Where(p => p.DELETE_DATE != null).Skip(input.pageNum * (input.pageNum - 1)).Take(input.pageSize).ToList();
                }
            }
            foreach (var user in usersInfo)
            {
                var userGroupName = _dbContextHelper.UserGroupModel.Where(p => p.USER_GROUP_ID.ToString() == user.USER_GROUP_ID).Select(p => p.USER_GROUP_NAME).FirstOrDefault();

                users.Add(new AdminUser()
                {
                    user_guid = user.GUID,
                    user_id = user.USER_ID,
                    email_adress = user.EMAIL_ADDRESS,
                    user_group_id = user.USER_GROUP_ID,
                    deliver_adress = user.DELIVERY_ADRESS,
                    nick_name = user.NICKNAME,
                    zip_code = user.ZIPCODE,
                    user_group_desc = userGroupName,
                    phone_number = user.PHONE_NUMBER
                });
            }
            return new AdminGetUserOutput()
            {
                data = users,
                page_count = listCount % input.pageSize == 0 ? (int)(listCount / input.pageSize) : (int)(listCount / input.pageSize) + 1,
                error_code = "2000",
                status = "200",
                msg = "",
            };
        }

        [HttpPost("CreateUserAdmin")]
        [Authorize]
        public OutputDTO CreateUserAdmin([FromBody] AdminCreateUserInput input)
        {
            var userClaim = HttpContext.User.Claims;
            var userGuid = userClaim.FirstOrDefault(c => c.Type == "UserGuid")?.Value;
            var userGroupId = userClaim.FirstOrDefault(c => c.Type == "UserGroupId")?.Value;
            if (userGroupId == "0")
            {
                return new OutputDTO()
                {
                    error_code = "2002",
                    status = "200",
                    msg = "Unauthorized",
                };
            }
            if (string.IsNullOrWhiteSpace(input.nick_name) || string.IsNullOrWhiteSpace(input.user_group_id) || string.IsNullOrWhiteSpace(input.zip_code) || string.IsNullOrWhiteSpace(input.adress) || string.IsNullOrWhiteSpace(input.email_adress) || string.IsNullOrWhiteSpace(input.password))
            {
                return new OutputDTO()
                {
                    error_code = "2001",
                    status = "200",
                    msg = "Form Can Not Be Null."
                };
            }

            var isExist = _dbContextHelper.UserInfo.Where(p => p.EMAIL_ADDRESS == input.email_adress).Count() > 0;
            if (isExist)
            {
                return new OutputDTO()
                {
                    error_code = "2001",
                    status = "200",
                    msg = "User Already Exist."
                };
            }

            var hashedPwd = _hashHelper.HashPassword(input.password);
            var userInfoGuid = Guid.NewGuid().ToString();
            Random random = new Random();
            var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString() + random.Next(100, 1000);

            UserAllModel userModel = new UserAllModel();
            userModel.GUID = Guid.NewGuid().ToString();
            userModel.USER_INFO_GUID = userInfoGuid;
            userModel.USER_ID = userId.ToString();
            userModel.SIGN_UP_DATETIME = DateTime.Now;

            UserInfoModel userInfoModel = new UserInfoModel();
            userInfoModel.GUID = userInfoGuid;
            userInfoModel.USER_GROUP_ID = input.user_group_id;
            userInfoModel.USER_PASSWORD = hashedPwd;
            userInfoModel.AVATAR = "";
            userInfoModel.USER_ID = userId.ToString();
            userInfoModel.NICKNAME = input.nick_name;
            userInfoModel.EMAIL_ADDRESS = input.email_adress;
            userInfoModel.DELIVERY_ADRESS = input.adress;
            userInfoModel.ZIPCODE = input.zip_code;
            userInfoModel.PHONE_NUMBER = input.phone_number;

            _dbContextHelper.Users.Add(userModel);
            _dbContextHelper.UserInfo.Add(userInfoModel);
            _dbContextHelper.SaveChanges();

            return new OutputDTO()
            {
                error_code = "2000",
                status = "200",
                msg = "Create User Succeed."
            };
        }

        [HttpPost("EditUserAdmin")]
        [Authorize]
        public OutputDTO EditUserAdmin([FromBody] AdminCreateUserInput input)
        {
            var userClaim = HttpContext.User.Claims;
            var userGuid = userClaim.FirstOrDefault(c => c.Type == "UserGuid")?.Value;
            var userGroupId = userClaim.FirstOrDefault(c => c.Type == "UserGroupId")?.Value;
            if (userGroupId == "0")
            {
                return new OutputDTO()
                {
                    error_code = "2002",
                    status = "200",
                    msg = "Unauthorized",
                };
            }
            var user = _dbContextHelper.UserInfo.Where(p => p.DELETE_DATE == null).Where(p => p.EMAIL_ADDRESS == input.email_adress).FirstOrDefault();
            if (user == null)
            {
                return new OutputDTO()
                {
                    error_code = "2001",
                    status = "200",
                    msg = "User Does Not Exist."
                };
            }
            if (!String.IsNullOrWhiteSpace(input.nick_name))
            {
                user.NICKNAME = input.nick_name;
            }

            if (!String.IsNullOrWhiteSpace(input.user_group_id))
            {
                user.USER_GROUP_ID = input.user_group_id;
            }
            if (!String.IsNullOrWhiteSpace(input.password))
            {
                user.USER_PASSWORD = _hashHelper.HashPassword(input.password);
            }
            if (!String.IsNullOrWhiteSpace(input.adress))
            {
                user.DELIVERY_ADRESS = input.adress;
            }
            if (!String.IsNullOrWhiteSpace(input.zip_code))
            {
                user.ZIPCODE = input.zip_code;
            }
            if (!String.IsNullOrWhiteSpace(input.phone_number))
            {
                user.PHONE_NUMBER = input.phone_number;
            }

            _dbContextHelper.SaveChanges();

            return new OutputDTO()
            {
                error_code = "2000",
                status = "200",
                msg = "Update User Succeed."
            };
        }

        [HttpPost("GetProductListAdmin")]
        [Authorize]
        public AdminGetProductOutput GetProductListAdmin([FromBody] AdminGetProductInput input)
        {
            var userClaim = HttpContext.User.Claims;
            var userGuid = userClaim.FirstOrDefault(c => c.Type == "UserGuid")?.Value;
            var userGroupId = userClaim.FirstOrDefault(c => c.Type == "UserGroupId")?.Value;
            if (userGroupId == "0")
            {
                return new AdminGetProductOutput()
                {
                    error_code = "2002",
                    status = "200",
                    msg = "Unauthorized",
                };
            }
            int listCount = 0;
            List<AdminProduct> products = new List<AdminProduct>();
            List<ProductInfoModel> productModel = new List<ProductInfoModel>();

            if (!string.IsNullOrWhiteSpace(input.keyword))
            {
                if (input.filter == "-1")
                {
                    List<int> productIds = _dbContextHelper.ProductDetail.Where(p => p.DELETE_DATE == null).Where(p => p.YEAR.ToLower().Contains(input.keyword.ToLower()) || p.BRAND.ToLower().Contains(input.keyword.ToLower()) || p.ENGINE.ToLower().Contains(input.keyword.ToLower()) || p.MODEL.ToLower().Contains(input.keyword.ToLower()) || p.FUEL_TYPE.ToLower().Contains(input.keyword.ToLower())).Select(p => p.PRODUCT_ID).ToList();

                    if (productIds.Count > 0)
                    {
                        listCount = _dbContextHelper.ProductInfo.Where(p => p.DELETE_DATE == null).Where(p => p.PRODUCT_NAME.ToLower().Contains(input.keyword.ToLower()) || productIds.Contains(p.PRODUCT_ID)).Count();
                        productModel = _dbContextHelper.ProductInfo.Where(p => p.DELETE_DATE == null).Where(p => p.PRODUCT_NAME.ToLower().Contains(input.keyword.ToLower()) || productIds.Contains(p.PRODUCT_ID)).OrderByDescending(p => p.PRODUCT_ID).Skip(input.pageSize * (input.pageNum - 1)).Take(input.pageSize).ToList();
                    }
                    else
                    {
                        listCount = _dbContextHelper.ProductInfo.Where(p => p.DELETE_DATE == null).Where(p => p.PRODUCT_NAME.ToLower().Contains(input.keyword.ToLower())).Count();
                        productModel = _dbContextHelper.ProductInfo.Where(p => p.DELETE_DATE == null).Where(p => p.PRODUCT_NAME.ToLower().Contains(input.keyword.ToLower())).OrderByDescending(p => p.PRODUCT_ID).Skip(input.pageSize * (input.pageNum - 1)).Take(input.pageSize).ToList();
                    }
                }
                else
                {
                    List<int> productIds = _dbContextHelper.ProductDetail.Where(p => p.YEAR.ToLower().Contains(input.keyword.ToLower()) || p.BRAND.ToLower().Contains(input.keyword.ToLower()) || p.ENGINE.ToLower().Contains(input.keyword.ToLower()) || p.MODEL.ToLower().Contains(input.keyword.ToLower()) || p.FUEL_TYPE.ToLower().Contains(input.keyword.ToLower())).Select(p => p.PRODUCT_ID).ToList();

                    listCount = _dbContextHelper.ProductInfo.Where(p => p.DELETE_DATE != null).Where(p => p.PRODUCT_NAME.ToLower().Contains(input.keyword.ToLower()) || productIds.Contains(p.PRODUCT_ID)).Count();
                    productModel = _dbContextHelper.ProductInfo.Where(p => p.DELETE_DATE != null).Where(p => p.PRODUCT_NAME.ToLower().Contains(input.keyword.ToLower()) || productIds.Contains(p.PRODUCT_ID)).OrderByDescending(p => p.PRODUCT_ID).Skip(input.pageSize * (input.pageNum - 1)).Take(input.pageSize).ToList();
                    //listCount = _dbContextHelper.ProductInfo.Where(p => p.DELETE_DATE != null).Where(p => p.PRODUCT_NAME.ToLower().Contains(input.keyword.ToLower()) || p.YEAR.ToLower().Contains(input.keyword.ToLower()) || p.BRAND.ToLower().Contains(input.keyword.ToLower()) || p.ENGINE.ToLower().Contains(input.keyword.ToLower()) || p.MODEL.ToLower().Contains(input.keyword.ToLower()) || p.FUEL_TYPE.ToLower().Contains(input.keyword.ToLower())).Count();
                    //productModel = _dbContextHelper.ProductInfo.Where(p => p.DELETE_DATE != null).Where(p => p.PRODUCT_NAME.ToLower().Contains(input.keyword.ToLower()) || p.YEAR.ToLower().Contains(input.keyword.ToLower()) || p.BRAND.ToLower().Contains(input.keyword.ToLower()) || p.ENGINE.ToLower().Contains(input.keyword.ToLower()) || p.MODEL.ToLower().Contains(input.keyword.ToLower()) || p.FUEL_TYPE.ToLower().Contains(input.keyword.ToLower())).OrderByDescending(p => p.PRODUCT_ID).Skip(input.pageSize * (input.pageNum - 1)).Take(input.pageSize).ToList();
                }
            }
            else
            {
                if (input.filter == "-1")
                {
                    listCount = _dbContextHelper.ProductInfo.Where(p => p.DELETE_DATE == null).Count();
                    productModel = _dbContextHelper.ProductInfo.Where(p => p.DELETE_DATE == null).OrderByDescending(p => p.PRODUCT_ID).Skip(input.pageSize * (input.pageNum - 1)).Take(input.pageSize).ToList();
                }
                else
                {
                    listCount = _dbContextHelper.ProductInfo.Where(p => p.DELETE_DATE != null).Count();
                    productModel = _dbContextHelper.ProductInfo.Where(p => p.DELETE_DATE != null).OrderByDescending(p => p.PRODUCT_ID).Skip(input.pageSize * (input.pageNum - 1)).Take(input.pageSize).ToList();
                }
            }
            foreach (var product in productModel)
            {
                var productAll = _dbContextHelper.Product.Where(p => p.PRODUCT_INFO_GUID == product.GUID).FirstOrDefault();
                var productDetailList = _dbContextHelper.ProductDetail.Where(p => p.PRODUCT_ID == product.PRODUCT_ID).ToList();
                var detailList = new List<ProductDetail>();
                foreach (var productDetail in productDetailList)
                {
                    detailList.Add(new ProductDetail()
                    {
                        year = productDetail.YEAR,
                        brand = productDetail.BRAND,
                        model = productDetail.MODEL,
                        engine = productDetail.ENGINE,
                        fuel_type = productDetail.FUEL_TYPE
                    });
                }

                products.Add(new AdminProduct()
                {
                    product_id = product.PRODUCT_ID,
                    product_name = product.PRODUCT_NAME,
                    product_description = product.PRODUCT_DESCRIPTION,
                    product_price = product.PRODUCT_PRICE,
                    product_detail = product.PRODUCT_DETAIL,
                    product_num = product.PRODUCT_NUM,
                    product_media1 = product.PRODUCT_MEDIA1,
                    product_media2 = product.PRODUCT_MEDIA2,
                    product_media3 = product.PRODUCT_MEDIA3,
                    upload_date = productAll != null ? productAll.UPLOAD_DATETIME.ToString() : "",
                    product_details = detailList
                });
            }
            return new AdminGetProductOutput()
            {
                data = products,
                page_count = listCount % input.pageSize == 0 ? (int)(listCount / input.pageSize) : (int)(listCount / input.pageSize) + 1,
                error_code = "2000",
                status = "200",
                msg = "",
            };
        }

        [HttpPost("CreateProductAdmin")]
        [Authorize]
        public AdminCreateProductOutput CreateProductAdmin([FromBody] AdminCreateProductInput input)
        {
            var userClaim = HttpContext.User.Claims;
            var userGuid = userClaim.FirstOrDefault(c => c.Type == "UserGuid")?.Value;
            var userGroupId = userClaim.FirstOrDefault(c => c.Type == "UserGroupId")?.Value;
            if (userGroupId == "0")
            {
                return new AdminCreateProductOutput()
                {
                    error_code = "2002",
                    status = "200",
                    msg = "Unauthorized",
                };
            }
            if (string.IsNullOrWhiteSpace(input.product_name) || string.IsNullOrWhiteSpace(input.product_price) || string.IsNullOrWhiteSpace(input.product_description) || string.IsNullOrWhiteSpace(input.product_detail) || string.IsNullOrWhiteSpace(input.product_num))
            {
                return new AdminCreateProductOutput()
                {
                    error_code = "2001",
                    status = "200",
                    msg = "Form Can Not Be Null."
                };
            }
            var productId = _dbContextHelper.ProductInfo.Select(p => p.PRODUCT_ID).OrderByDescending(p => p).FirstOrDefault();
            int number = productId + 1;
            var isExist = _dbContextHelper.ProductInfo.Where(p => p.PRODUCT_ID == number).Count() > 0;
            if (isExist)
            {
                return new AdminCreateProductOutput()
                {
                    error_code = "2001",
                    status = "200",
                    msg = "Network congestion, please try again."
                };
            }

            var productInfoGuid = Guid.NewGuid().ToString();
            ProductAllModel pAModel = new ProductAllModel();
            pAModel.GUID = Guid.NewGuid().ToString();
            pAModel.PRODUCT_INFO_GUID = productInfoGuid;
            pAModel.PRODUCT_ID = number;
            pAModel.PRODUCT_NUM = input.product_num;
            pAModel.UPLOAD_DATETIME = DateTime.Now;
            ProductInfoModel pIModel = new ProductInfoModel();
            pIModel.GUID = productInfoGuid;
            pIModel.PRODUCT_ID = number;
            pIModel.PRODUCT_NUM = input.product_num;
            pIModel.PRODUCT_NAME = input.product_name;
            pIModel.PRODUCT_PRICE = input.product_price;
            pIModel.PRODUCT_DETAIL = input.product_detail;
            pIModel.PRODUCT_DESCRIPTION = input.product_description;
            //pIModel.YEAR = input.year;
            //pIModel.BRAND = input.brand;
            //pIModel.MODEL = input.model;
            //pIModel.ENGINE = input.engine;
            //pIModel.FUEL_TYPE = input.fuel_type;
            pIModel.PRODUCT_MEDIA1 = "";
            pIModel.PRODUCT_MEDIA2 = "";
            pIModel.PRODUCT_MEDIA3 = "";
            pIModel.PRODUCT_MEDIA4 = "";


            _dbContextHelper.Product.Add(pAModel);
            _dbContextHelper.ProductInfo.Add(pIModel);
            _dbContextHelper.SaveChanges();

            return new AdminCreateProductOutput()
            {
                product_id = number,
                error_code = "2000",
                status = "200",
                msg = "Create Product Succeed."
            };
        }



        [HttpPost("SaveProductDetailAdmin")]
        [Authorize]
        public OutputDTO SaveProductDetailAdmin([FromBody] AdminCreateProductDetailInput input)
        {
            if (input.product_details.Count > 0)
            {
                var detail = _dbContextHelper.ProductDetail.Where(p => p.PRODUCT_ID == input.product_id).ToList();
                foreach (var item in detail)
                {
                    item.DELETE_DATE = DateTime.Now;
                }
            }
            foreach (var item in input.product_details)
            {
                if (!string.IsNullOrWhiteSpace(item.year) && !string.IsNullOrWhiteSpace(item.engine) && !string.IsNullOrWhiteSpace(item.model) && !string.IsNullOrWhiteSpace(item.fuel_type) && !string.IsNullOrWhiteSpace(item.brand))
                {
                    _dbContextHelper.ProductDetail.Add(new ProductDetailModel()
                    {
                        GUID = Guid.NewGuid().ToString(),
                        PRODUCT_ID = input.product_id,
                        YEAR = item.year,
                        BRAND = item.brand,
                        ENGINE = item.engine,
                        MODEL = item.model,
                        FUEL_TYPE = item.fuel_type,
                    });
                }
            }
            if (input.product_details.Count > 0)
                _dbContextHelper.SaveChanges();
            return new OutputDTO()
            {
                error_code = "2000",
                status = "200",
                msg = "Create Product Succeed."
            };
        }


        [HttpPost("EditProductAdmin")]
        [Authorize]
        public OutputDTO EditProductAdmin([FromBody] AdminEditProductInput input)
        {
            var userClaim = HttpContext.User.Claims;
            var userGuid = userClaim.FirstOrDefault(c => c.Type == "UserGuid")?.Value;
            var userGroupId = userClaim.FirstOrDefault(c => c.Type == "UserGroupId")?.Value;
            var productId = int.Parse(input.product_id);
            if (userGroupId == "0")
            {
                return new OutputDTO()
                {
                    error_code = "2002",
                    status = "200",
                    msg = "Unauthorized",
                };
            }
            var product = _dbContextHelper.Product.Where(p => p.DELETE_DATE == null).Where(p => p.PRODUCT_ID == productId).FirstOrDefault();
            var productInfo = _dbContextHelper.ProductInfo.Where(p => p.DELETE_DATE == null).Where(p => p.PRODUCT_ID == productId).FirstOrDefault();

            if (productInfo == null || product == null)
            {
                return new OutputDTO()
                {
                    error_code = "2001",
                    status = "200",
                    msg = "Product Not Exist."
                };
            }
            if (!string.IsNullOrWhiteSpace(input.product_num))
            {
                product.PRODUCT_NUM = input.product_num;
            }
            product.UPLOAD_DATETIME = DateTime.Now;
            if (!string.IsNullOrWhiteSpace(input.product_num))
            {
                productInfo.PRODUCT_NUM = input.product_num;
            }
            if (!string.IsNullOrWhiteSpace(input.product_name))
            {
                productInfo.PRODUCT_NAME = input.product_name;
            }
            if (!string.IsNullOrWhiteSpace(input.product_price))
            {
                productInfo.PRODUCT_PRICE = input.product_price;
            }
            if (!string.IsNullOrWhiteSpace(input.product_detail))
            {
                productInfo.PRODUCT_DETAIL = input.product_detail;
            }
            if (!string.IsNullOrWhiteSpace(input.product_description))
            {
                productInfo.PRODUCT_DESCRIPTION = input.product_description;
            }

            _dbContextHelper.SaveChanges();
            return new OutputDTO()
            {
                error_code = "2000",
                status = "200",
                msg = "Update Product Succeed."
            };
        }

        [HttpPost("SaveOrderDeliverExpressInfoAdmin")]
        [Authorize]
        public OutputDTO SaveOrderDeliverExpressInfoAdmin([FromBody] SaveOrderExpressInfoInput input)
        {
            var userClaim = HttpContext.User.Claims;
            var userGuid = userClaim.FirstOrDefault(c => c.Type == "UserGuid")?.Value;
            var userGroupId = userClaim.FirstOrDefault(c => c.Type == "UserGroupId")?.Value;
            if (userGroupId == "0")
            {
                return new OutputDTO()
                {
                    error_code = "2002",
                    status = "200",
                    msg = "Unauthorized",
                };
            }
            if (string.IsNullOrWhiteSpace(input.order_id))
            {
                return new OutputDTO()
                {
                    error_code = "2001",
                    status = "200",
                    msg = "Save Express Info Failed."
                };
            }
            var orderUserGuid = _dbContextHelper.OrderAllModel.Where(p => p.ORDER_ID == input.order_id).Select(p => p.USER_GUID).FirstOrDefault();
            if (orderUserGuid == null)
            {
                return new OutputDTO()
                {
                    error_code = "2001",
                    status = "200",
                    msg = "Save Express Info Failed."
                };
            }
            var oldExpressInfo = _dbContextHelper.OrderTrackingNumberModel.Where(p => p.DELETE_DATE == null && p.ORDER_ID == input.order_id && p.TRACKING_NUMBER_TYPE == "DELIVER").ToList();
            foreach (var old in oldExpressInfo)
            {
                old.DELETE_DATE = DateTime.Now;
            }
            foreach (var item in input.express_info)
            {
                OrderTrackingNumberModel model = new OrderTrackingNumberModel();
                model.GUID = Guid.NewGuid().ToString();
                model.ORDER_ID = input.order_id;
                model.TRACKING_NUMBER_TYPE = "DELIVER";
                model.TRACKING_NUMBER = item.tracking_number;
                model.EXPRESS_COMPANY = item.express_company;
                model.USER_GUID = orderUserGuid;
                _dbContextHelper.OrderTrackingNumberModel.Add(model);
            }
            _dbContextHelper.SaveChanges();
            return new OutputDTO()
            {
                error_code = "2000",
                status = "200",
                msg = "Save Express Info Succeed."
            };
        }

        [HttpPost("GetOrderExpressInfoAdmin")]
        [Authorize]
        public GetOrderExpressInfoOutput GetOrderExpressInfoAdmin(GetOrderExpressInfoInput input)
        {
            var userClaim = HttpContext.User.Claims;
            var userGuid = userClaim.FirstOrDefault(c => c.Type == "UserGuid")?.Value;
            var userGroupId = userClaim.FirstOrDefault(c => c.Type == "UserGroupId")?.Value;
            if (userGroupId == "0")
            {
                return new GetOrderExpressInfoOutput()
                {
                    error_code = "2002",
                    status = "200",
                    msg = "Unauthorized",
                };
            }
            if (string.IsNullOrWhiteSpace(input.order_id))
            {
                return new GetOrderExpressInfoOutput()
                {
                    error_code = "2001",
                    status = "200",
                    msg = "Get Express Info Failed."
                };
            }
            var expressInfo = _dbContextHelper.OrderTrackingNumberModel.Where(p => p.DELETE_DATE == null && p.ORDER_ID == input.order_id && p.TRACKING_NUMBER_TYPE == "DELIVER").ToList();
            List<ExpressInfo> expressList = new List<ExpressInfo>();
            foreach (var item in expressInfo)
            {
                expressList.Add(new ExpressInfo()
                {
                    express_company = (item.EXPRESS_COMPANY != null) ? item.EXPRESS_COMPANY : "",
                    tracking_number = (item.TRACKING_NUMBER != null) ? item.TRACKING_NUMBER : ""
                });
            }

            return new GetOrderExpressInfoOutput()
            {
                express_info = expressList,
                error_code = "2000",
                status = "200",
                msg = "Get Express Info Succeed."
            };
        }

        /// <summary>
        /// 获取订单列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("GetOrderListAdmin")]
        [Authorize]
        public GetOrderListOutput GetOrderListAdmin([FromBody] GetOrderListInput input)
        {
            var userClaim = HttpContext.User.Claims;
            var userGuid = userClaim.FirstOrDefault(c => c.Type == "UserGuid")?.Value;
            var userGroupId = userClaim.FirstOrDefault(c => c.Type == "UserGroupId")?.Value;
            if (userGroupId == "0")
            {
                return new GetOrderListOutput()
                {
                    error_code = "2002",
                    status = "200",
                    msg = "Unauthorized",
                };
            }
            List<Order> orders = new List<Order>();
            List<OrderAllModel> orderList;
            int listCount = 0;
            if (!string.IsNullOrWhiteSpace(input.filter) && input.filter != "-1" && input.filter != "-2")
            {
                if (!string.IsNullOrWhiteSpace(input.keyword))
                {
                    var productIdList = _dbContextHelper.ProductInfo.Where(p => p.PRODUCT_NAME.Contains(input.keyword)).Select(p => p.PRODUCT_ID).ToList();
                    var userGuidList = _dbContextHelper.UserInfo.Where(p => p.EMAIL_ADDRESS.Contains(input.keyword)).Select(p => p.GUID).ToList();

                    listCount = _dbContextHelper.OrderAllModel.Where(p => p.DELETE_DATE == null).Where(b => b.ORDER_STATUS_CODE == input.filter).Where(p => productIdList.Contains(p.PRODUCT_ID) || userGuidList.Contains(p.USER_GUID) || p.ORDER_ID.Contains(input.keyword)).Count();
                    orderList = _dbContextHelper.OrderAllModel.Where(p => p.DELETE_DATE == null).Where(b => b.ORDER_STATUS_CODE == input.filter).Where(p => productIdList.Contains(p.PRODUCT_ID) || userGuidList.Contains(p.USER_GUID) || p.ORDER_ID.Contains(input.keyword)).OrderByDescending(p => p.CREATE_DATETIME).Skip(input.pageSize * (input.pageNum - 1)).Take(input.pageSize).ToList();
                }
                else
                {
                    listCount = _dbContextHelper.OrderAllModel.Where(p => p.DELETE_DATE == null).Where(b => b.ORDER_STATUS_CODE == input.filter).Count();
                    orderList = _dbContextHelper.OrderAllModel.Where(p => p.DELETE_DATE == null).Where(b => b.ORDER_STATUS_CODE == input.filter).OrderByDescending(p => p.CREATE_DATETIME).Skip(input.pageSize * (input.pageNum - 1)).Take(input.pageSize).ToList();
                }
            }
            else
            {
                if (input.filter != "-2")
                {
                    if (!string.IsNullOrWhiteSpace(input.keyword))
                    {
                        var productIdList = _dbContextHelper.ProductInfo.Where(p => p.PRODUCT_NAME.Contains(input.keyword)).Select(p => p.PRODUCT_ID).ToList();
                        var userGuidList = _dbContextHelper.UserInfo.Where(p => p.EMAIL_ADDRESS.Contains(input.keyword)).Select(p => p.GUID).ToList();

                        listCount = _dbContextHelper.OrderAllModel.Where(p => p.DELETE_DATE == null).Where(p => productIdList.Contains(p.PRODUCT_ID) || userGuidList.Contains(p.USER_GUID) || p.ORDER_ID.Contains(input.keyword)).Count();
                        orderList = _dbContextHelper.OrderAllModel.Where(p => p.DELETE_DATE == null).Where(p => productIdList.Contains(p.PRODUCT_ID) || userGuidList.Contains(p.USER_GUID) || p.ORDER_ID.Contains(input.keyword)).OrderByDescending(p => p.CREATE_DATETIME).Skip(input.pageSize * (input.pageNum - 1)).Take(input.pageSize).ToList();
                    }
                    else
                    {
                        listCount = _dbContextHelper.OrderAllModel.Where(p => p.DELETE_DATE == null).Count();
                        orderList = _dbContextHelper.OrderAllModel.Where(p => p.DELETE_DATE == null).OrderByDescending(p => p.CREATE_DATETIME).Skip(input.pageSize * (input.pageNum - 1)).Take(input.pageSize).ToList();
                    }
                }
                else
                {
                    if (!string.IsNullOrWhiteSpace(input.keyword))
                    {
                        var productIdList = _dbContextHelper.ProductInfo.Where(p => p.PRODUCT_NAME.Contains(input.keyword)).Select(p => p.PRODUCT_ID).ToList();
                        var userGuidList = _dbContextHelper.UserInfo.Where(p => p.EMAIL_ADDRESS.Contains(input.keyword)).Select(p => p.GUID).ToList();

                        listCount = _dbContextHelper.OrderAllModel.Where(p => p.DELETE_DATE != null).Where(p => productIdList.Contains(p.PRODUCT_ID) || userGuidList.Contains(p.USER_GUID) || p.ORDER_ID.Contains(input.keyword)).Count();
                        orderList = _dbContextHelper.OrderAllModel.Where(p => p.DELETE_DATE != null).Where(p => productIdList.Contains(p.PRODUCT_ID) || userGuidList.Contains(p.USER_GUID) || p.ORDER_ID.Contains(input.keyword)).OrderByDescending(p => p.CREATE_DATETIME).Skip(input.pageSize * (input.pageNum - 1)).Take(input.pageSize).ToList();
                    }
                    else
                    {
                        listCount = _dbContextHelper.OrderAllModel.Where(p => p.DELETE_DATE != null).Count();
                        orderList = _dbContextHelper.OrderAllModel.Where(p => p.DELETE_DATE != null).OrderByDescending(p => p.CREATE_DATETIME).Skip(input.pageSize * (input.pageNum - 1)).Take(input.pageSize).ToList();
                    }
                }
            }
            foreach (var order in orderList)
            {
                var orderInfo = _dbContextHelper.OrderInfoModel.Where(p => p.GUID == order.ORDER_INFO_GUID).FirstOrDefault();
                var product = _dbContextHelper.ProductInfo.Where(p => p.PRODUCT_ID == order.PRODUCT_ID).FirstOrDefault();
                UserInfoModel userInfo = null;

                userInfo = _dbContextHelper.UserInfo.Where(p => p.GUID == order.USER_GUID).FirstOrDefault();

                if (product != null && orderInfo != null)
                {
                    orders.Add(new Order()
                    {
                        product_id = order.PRODUCT_ID.ToString(),
                        product_img = product.PRODUCT_MEDIA1,
                        product_name = product.PRODUCT_NAME,
                        order_id = order.ORDER_ID,
                        order_num = order.ORDER_NUM,
                        total_price = orderInfo.ORDER_TOTAL_PRICE,
                        order_status_code = order.ORDER_STATUS_CODE,
                        order_status_desc = order.ORDER_STATUS_DESC,
                        create_date = order.CREATE_DATETIME.ToString(),
                        tracking_number = orderInfo.TRACKING_NUMBER,
                        tracking_img = orderInfo.ORDER_MEDIA1,
                        deliver_date = orderInfo.DELIVERY_DATE == null ? "" : orderInfo.DELIVERY_DATE.ToString(),
                        return_tracking_number = orderInfo.RETURN_TRACKING_NUMBER,
                        return_tracking_img = orderInfo.ORDER_MEDIA2,
                        return_reason = orderInfo.RETURN_REASON,
                        return_date = orderInfo.RETURN_DATE == null ? "" : orderInfo.RETURN_DATE.ToString(),
                        payment_id = orderInfo.PAYMENT_ID,
                        return_reason_tip = orderInfo.ADMIN_RETURN_REASON_TIP,
                        return_number_tip = orderInfo.ADMIN_RETURN_NUMBER_TIP,
                        user_name = userInfo != null ? userInfo.NICKNAME : null
                    });
                }
            }
            return new GetOrderListOutput()
            {
                data = orders,
                page_count = listCount % input.pageSize == 0 ? (int)(listCount / input.pageSize) : (int)(listCount / input.pageSize) + 1,
                error_code = "2000",
                status = "200",
                msg = ""
            };
        }

        [HttpPost("GetUserBinListAdmin")]
        [Authorize]
        public AdminGetUserOutput GetUserBinListAdmin([FromBody] AdminGetUserInput input)
        {
            var userClaim = HttpContext.User.Claims;
            var userGuid = userClaim.FirstOrDefault(c => c.Type == "UserGuid")?.Value;
            var userGroupId = userClaim.FirstOrDefault(c => c.Type == "UserGroupId")?.Value;
            if (userGroupId == "0")
            {
                return new AdminGetUserOutput()
                {
                    error_code = "2002",
                    status = "200",
                    msg = "Unauthorized",
                };
            }
            int listCount = 0;
            List<AdminUser> users = new List<AdminUser>();
            List<UserInfoModel> usersInfo = new List<UserInfoModel>();

            if (!string.IsNullOrWhiteSpace(input.keyword))
            {
                listCount = _dbContextHelper.UserInfo.Where(p => (p.EMAIL_ADDRESS.ToLower().Contains(input.keyword.ToLower()) || p.NICKNAME.ToLower().Contains(input.keyword.ToLower())) && (p.DELETE_DATE != null)).Count();
                usersInfo = _dbContextHelper.UserInfo.Where(p => (p.EMAIL_ADDRESS.ToLower().Contains(input.keyword.ToLower()) || p.NICKNAME.ToLower().Contains(input.keyword.ToLower())) && (p.DELETE_DATE != null)).OrderByDescending(p => p.DELETE_DATE).Skip(input.pageNum * (input.pageNum - 1)).Take(input.pageSize).ToList();
            }
            else
            {
                listCount = _dbContextHelper.UserInfo.Where(p => p.DELETE_DATE != null).Count();
                usersInfo = _dbContextHelper.UserInfo.Where(p => p.DELETE_DATE != null).OrderByDescending(p => p.DELETE_DATE).Skip(input.pageNum * (input.pageNum - 1)).Take(input.pageSize).ToList();
            }
            foreach (var user in usersInfo)
            {
                users.Add(new AdminUser()
                {
                    user_guid = user.GUID,
                    user_id = user.USER_ID,
                    email_adress = user.EMAIL_ADDRESS,
                    user_group_id = user.USER_GROUP_ID,
                    deliver_adress = user.DELIVERY_ADRESS,
                    nick_name = user.NICKNAME,
                    zip_code = user.ZIPCODE
                });
            }
            return new AdminGetUserOutput()
            {
                data = users,
                page_count = listCount % input.pageSize == 0 ? (int)(listCount / input.pageSize) : (int)(listCount / input.pageSize) + 1,
                error_code = "2000",
                status = "200",
                msg = "",
            };
        }

        [HttpPost("GetProductBinListAdmin")]
        [Authorize]
        public AdminGetProductOutput GetProductBinListAdmin([FromBody] AdminGetProductInput input)
        {
            var userClaim = HttpContext.User.Claims;
            var userGuid = userClaim.FirstOrDefault(c => c.Type == "UserGuid")?.Value;
            var userGroupId = userClaim.FirstOrDefault(c => c.Type == "UserGroupId")?.Value;
            if (userGroupId == "0")
            {
                return new AdminGetProductOutput()
                {
                    error_code = "2002",
                    status = "200",
                    msg = "Unauthorized",
                };
            }
            int listCount = 0;
            List<AdminProduct> products = new List<AdminProduct>();
            List<ProductInfoModel> productModel = new List<ProductInfoModel>();

            if (!string.IsNullOrWhiteSpace(input.keyword))
            {
                List<int> productIds = _dbContextHelper.ProductDetail.Where(p => p.DELETE_DATE == null).Where(p => p.YEAR.ToLower().Contains(input.keyword.ToLower()) || p.BRAND.ToLower().Contains(input.keyword.ToLower()) || p.ENGINE.ToLower().Contains(input.keyword.ToLower()) || p.MODEL.ToLower().Contains(input.keyword.ToLower()) || p.FUEL_TYPE.ToLower().Contains(input.keyword.ToLower())).Select(p => p.PRODUCT_ID).ToList();

                listCount = _dbContextHelper.ProductInfo.Where(p => p.DELETE_DATE == null).Where(p => p.PRODUCT_NAME.ToLower().Contains(input.keyword.ToLower()) && productIds.Contains(p.PRODUCT_ID)).Count();
                productModel = _dbContextHelper.ProductInfo.Where(p => p.DELETE_DATE == null).Where(p => p.PRODUCT_NAME.ToLower().Contains(input.keyword.ToLower()) && productIds.Contains(p.PRODUCT_ID)).OrderByDescending(p => p.PRODUCT_ID).Skip(input.pageSize * (input.pageNum - 1)).Take(input.pageSize).ToList();
            }
            else
            {
                listCount = _dbContextHelper.ProductInfo.Where(p => p.DELETE_DATE != null).Count();
                productModel = _dbContextHelper.ProductInfo.Where(p => p.DELETE_DATE != null).Skip(input.pageNum * (input.pageNum - 1)).Take(input.pageSize).ToList();
            }
            foreach (var product in productModel)
            {
                products.Add(new AdminProduct()
                {
                    product_id = product.PRODUCT_ID,
                    product_name = product.PRODUCT_NAME,
                    product_description = product.PRODUCT_DESCRIPTION,
                    product_price = product.PRODUCT_PRICE,
                    product_detail = product.PRODUCT_DETAIL,
                    product_num = product.PRODUCT_NUM,
                    product_media1 = product.PRODUCT_MEDIA1,
                    product_media2 = product.PRODUCT_MEDIA2,
                    product_media3 = product.PRODUCT_MEDIA3,
                });
            }
            return new AdminGetProductOutput()
            {
                data = products,
                page_count = listCount % input.pageSize == 0 ? (int)(listCount / input.pageSize) : (int)(listCount / input.pageSize) + 1,
                error_code = "2000",
                status = "200",
                msg = "",
            };
        }

        [HttpPost("GetOrderBinListAdmin")]
        [Authorize]
        public GetOrderListOutput GetOrderBinListAdmin([FromBody] GetOrderListInput input)
        {
            var userClaim = HttpContext.User.Claims;
            var userGuid = userClaim.FirstOrDefault(c => c.Type == "UserGuid")?.Value;
            var userGroupId = userClaim.FirstOrDefault(c => c.Type == "UserGroupId")?.Value;
            if (userGroupId == "0")
            {
                return new GetOrderListOutput()
                {
                    error_code = "2002",
                    status = "200",
                    msg = "Unauthorized",
                };
            }
            List<Order> orders = new List<Order>();
            var orderList = _dbContextHelper.OrderAllModel.Where(b => (b.USER_GUID == userGuid) && b.DELETE_DATE != null).ToList();
            foreach (var order in orderList)
            {
                var orderInfo = _dbContextHelper.OrderInfoModel.Where(b => b.GUID == order.ORDER_INFO_GUID && order.ORDER_INFO_GUID == b.GUID).FirstOrDefault();
                var product = _dbContextHelper.ProductInfo.Where(p => p.PRODUCT_ID == order.PRODUCT_ID).FirstOrDefault();

                if (product != null && orderInfo != null)
                {
                    orders.Add(new Order()
                    {
                        product_img = product.PRODUCT_MEDIA1,
                        product_name = product.PRODUCT_NAME,
                        order_id = order.ORDER_ID,
                        order_num = order.ORDER_NUM,
                        total_price = orderInfo.ORDER_TOTAL_PRICE,
                        order_status_code = order.ORDER_STATUS_CODE,
                        order_status_desc = order.ORDER_STATUS_DESC,
                        create_date = order.CREATE_DATETIME.ToString(),
                        tracking_number = orderInfo.TRACKING_NUMBER,
                        tracking_img = orderInfo.ORDER_MEDIA1,
                        deliver_date = orderInfo.DELIVERY_DATE == null ? "" : orderInfo.DELIVERY_DATE.ToString(),
                        return_tracking_number = orderInfo.RETURN_TRACKING_NUMBER,
                        return_tracking_img = orderInfo.ORDER_MEDIA2,
                        return_reason = orderInfo.RETURN_REASON
                    });
                }
            }
            return new GetOrderListOutput()
            {
                data = orders,
                error_code = "2000",
                status = "200",
                msg = ""
            };
        }


        [HttpPost("EditOrderTrackingAdmin")]
        [Authorize]
        public OutputDTO EditOrderTrackingAdmin(AdminEditOrderTrackingInput input)
        {
            var userClaim = HttpContext.User.Claims;
            var userGuid = userClaim.FirstOrDefault(c => c.Type == "UserGuid")?.Value;
            var userGroupId = userClaim.FirstOrDefault(c => c.Type == "UserGroupId")?.Value;
            //string imagePath = null;
            if (userGroupId == "0")
            {
                return new OutputDTO()
                {
                    error_code = "2002",
                    status = "200",
                    msg = "Unauthorized",
                };
            }
            //if (!string.IsNullOrWhiteSpace(input.tracking_image) && !string.IsNullOrWhiteSpace(input.order_id))
            //{
            //    _fileHelper.DownloadImageByBase64(input.tracking_image, "tracking" + input.order_id, "./FileServer/public/orders");
            //    imagePath = "orders/" + "tracking" + input.order_id + ".png";
            //}
            if ((!string.IsNullOrWhiteSpace(input.order_id)))
            {
                var order = _dbContextHelper.OrderInfoModel.Where(p => p.ORDER_ID == input.order_id).FirstOrDefault();
                var orderAll = _dbContextHelper.OrderAllModel.Where(p => p.ORDER_ID == input.order_id).FirstOrDefault();
                if (order != null && orderAll != null)
                {
                    if (orderAll.ORDER_STATUS_CODE != ((int)StatusEnum.Undelivered).ToString() && orderAll.ORDER_STATUS_CODE != ((int)StatusEnum.Delivered).ToString())
                    {
                        return new OutputDTO()
                        {
                            error_code = "2001",
                            status = "200",
                            msg = "Update Order failed",
                        };
                    }
                    if (orderAll.ORDER_STATUS_CODE != ((int)StatusEnum.Delivered).ToString())
                    {
                        orderAll.ORDER_STATUS_CODE = ((int)StatusEnum.Delivered).ToString();
                        orderAll.ORDER_STATUS_DESC = Enum.GetName(typeof(StatusEnum), StatusEnum.Delivered) ?? "Delivered";
                    }
                    //if (imagePath != null)
                    //{
                    //    order.ORDER_MEDIA1 = imagePath;
                    //}
                    if (!string.IsNullOrWhiteSpace(input.tracking_number))
                    {
                        order.TRACKING_NUMBER = input.tracking_number;
                    }
                    if (!string.IsNullOrWhiteSpace(input.return_number_tip))
                    {
                        order.ADMIN_RETURN_NUMBER_TIP = input.return_number_tip;
                    }
                    if (!string.IsNullOrWhiteSpace(input.return_reason_tip))
                    {
                        order.ADMIN_RETURN_REASON_TIP = input.return_reason_tip;
                    }
                    if (order.DELIVERY_DATE == null)
                    {
                        order.DELIVERY_DATE = DateTime.Now;
                    }
                    _dbContextHelper.SaveChanges();
                }
            }
            return new OutputDTO()
            {
                error_code = "2000",
                status = "200",
                msg = "Update Order Succeed."
            };
        }

        [HttpPost("ConfirmReturnAdmin")]
        [Authorize]
        public OutputDTO ConfirmReturnAdmin(AdminConfirmReturnInput input)
        {
            var userClaim = HttpContext.User.Claims;
            var userGuid = userClaim.FirstOrDefault(c => c.Type == "UserGuid")?.Value;
            var userGroupId = userClaim.FirstOrDefault(c => c.Type == "UserGroupId")?.Value;
            if (userGroupId == "0")
            {
                return new GetOrderListOutput()
                {
                    error_code = "2002",
                    status = "200",
                    msg = "Unauthorized",
                };
            }

            var orderAll = _dbContextHelper.OrderAllModel.Where(p => p.ORDER_ID == input.order_id && p.ORDER_STATUS_CODE == ((int)StatusEnum.Processing).ToString()).FirstOrDefault();
            if (orderAll != null)
            {
                orderAll.ORDER_STATUS_CODE = ((int)StatusEnum.Returned).ToString();
                orderAll.ORDER_STATUS_DESC = Enum.GetName(typeof(StatusEnum), StatusEnum.Returned) ?? "Returned";
                _dbContextHelper.SaveChanges();
            }

            return new OutputDTO()
            {
                error_code = "2000",
                status = "200",
                msg = "Confirm Return Succeed."
            };
        }

        [HttpPost("RevokeReturnAdmin")]
        [Authorize]
        public OutputDTO RevokeReturnAdmin(AdminConfirmReturnInput input)
        {
            var userClaim = HttpContext.User.Claims;
            var userGuid = userClaim.FirstOrDefault(c => c.Type == "UserGuid")?.Value;
            var userGroupId = userClaim.FirstOrDefault(c => c.Type == "UserGroupId")?.Value;
            if (userGroupId == "0")
            {
                return new GetOrderListOutput()
                {
                    error_code = "2002",
                    status = "200",
                    msg = "Unauthorized",
                };
            }

            var orderAll = _dbContextHelper.OrderAllModel.Where(p => p.ORDER_ID == input.order_id && p.ORDER_STATUS_CODE == ((int)StatusEnum.Processing).ToString()).FirstOrDefault();
            if (orderAll != null)
            {
                orderAll.ORDER_STATUS_CODE = ((int)StatusEnum.Delivered).ToString();
                orderAll.ORDER_STATUS_DESC = Enum.GetName(typeof(StatusEnum), StatusEnum.Delivered) ?? "Delivered";
                _dbContextHelper.SaveChanges();
            }

            return new OutputDTO()
            {
                error_code = "2000",
                status = "200",
                msg = "Confirm Return Succeed."
            };
        }

        [HttpPost("DeleteUserAdmin")]
        [Authorize]
        public OutputDTO DeleteUserAdmin(AdminDeleteInput input)
        {
            var userClaim = HttpContext.User.Claims;
            var userGuid = userClaim.FirstOrDefault(c => c.Type == "UserGuid")?.Value;
            var userGroupId = userClaim.FirstOrDefault(c => c.Type == "UserGroupId")?.Value;
            if (userGroupId == "0")
            {
                return new GetOrderListOutput()
                {
                    error_code = "2002",
                    status = "200",
                    msg = "Unauthorized",
                };
            }

            if (!string.IsNullOrWhiteSpace(input.id))
            {
                var user = _dbContextHelper.Users.Where(p => p.USER_ID == input.id).FirstOrDefault();
                var userInfo = _dbContextHelper.UserInfo.Where(p => p.USER_ID == input.id).FirstOrDefault();
                if (userInfo != null && user != null)
                {
                    user.DELETE_DATE = DateTime.Now;
                    userInfo.DELETE_DATE = DateTime.Now;

                    _dbContextHelper.SaveChanges();

                    return new OutputDTO()
                    {
                        error_code = "2000",
                        status = "200",
                        msg = "Delete Succeed."
                    };
                }
                else
                {
                    return new GetOrderListOutput()
                    {
                        error_code = "2001",
                        status = "200",
                        msg = "User Not Exist",
                    };
                }
            }

            return new OutputDTO()
            {
                error_code = "2000",
                status = "200",
                msg = "Delete Succeed."
            };
        }

        [HttpPost("DeleteProductAdmin")]
        [Authorize]
        public OutputDTO DeleteProductAdmin(AdminDeleteInput input)
        {
            var userClaim = HttpContext.User.Claims;
            var userGuid = userClaim.FirstOrDefault(c => c.Type == "UserGuid")?.Value;
            var userGroupId = userClaim.FirstOrDefault(c => c.Type == "UserGroupId")?.Value;
            if (userGroupId == "0")
            {
                return new GetOrderListOutput()
                {
                    error_code = "2002",
                    status = "200",
                    msg = "Unauthorized",
                };
            }

            if (!string.IsNullOrWhiteSpace(input.id))
            {
                int productId = int.Parse(input.id);
                var product = _dbContextHelper.Product.Where(p => p.PRODUCT_ID == productId).FirstOrDefault();
                var productInfo = _dbContextHelper.ProductInfo.Where(p => p.PRODUCT_ID == productId).FirstOrDefault();
                var productDetail = _dbContextHelper.ProductDetail.Where(p => p.PRODUCT_ID == productId).ToList();

                if (productInfo != null && product != null)
                {
                    product.DELETE_DATE = DateTime.Now;
                    productInfo.DELETE_DATE = DateTime.Now;
                    foreach (var detail in productDetail)
                    {
                        detail.DELETE_DATE = DateTime.Now;
                    }
                    _dbContextHelper.SaveChanges();

                    return new OutputDTO()
                    {
                        error_code = "2000",
                        status = "200",
                        msg = "Delete Succeed."
                    };
                }
                else
                {
                    return new GetOrderListOutput()
                    {
                        error_code = "2001",
                        status = "200",
                        msg = "Product Not Exist",
                    };
                }
            }
            return new OutputDTO()
            {
                error_code = "2000",
                status = "200",
                msg = "Delete Succeed."
            };
        }

        [HttpPost("DeleteOrderAdmin")]
        [Authorize]
        public OutputDTO DeleteOrderAdmin(AdminDeleteInput input)
        {
            var userClaim = HttpContext.User.Claims;
            var userGuid = userClaim.FirstOrDefault(c => c.Type == "UserGuid")?.Value;
            var userGroupId = userClaim.FirstOrDefault(c => c.Type == "UserGroupId")?.Value;
            if (userGroupId == "0")
            {
                return new GetOrderListOutput()
                {
                    error_code = "2002",
                    status = "200",
                    msg = "Unauthorized",
                };
            }

            if (!string.IsNullOrWhiteSpace(input.id))
            {
                var order = _dbContextHelper.OrderAllModel.Where(p => p.ORDER_ID == input.id).FirstOrDefault();
                var orderInfo = _dbContextHelper.OrderInfoModel.Where(p => p.ORDER_ID == input.id).FirstOrDefault();
                if (orderInfo != null && order != null)
                {
                    order.DELETE_DATE = DateTime.Now;
                    order.RECOVER_STATUS_CODE = order.ORDER_STATUS_CODE;
                    order.RECOVER_STATUS_DESC = order.ORDER_STATUS_DESC;

                    order.ORDER_STATUS_CODE = ((int)StatusEnum.Deleted).ToString();
                    order.ORDER_STATUS_DESC = Enum.GetName(typeof(StatusEnum), StatusEnum.Deleted) ?? "Deleted";
                    orderInfo.DELETE_DATE = DateTime.Now;
                    _dbContextHelper.SaveChanges();

                    return new OutputDTO()
                    {
                        error_code = "2000",
                        status = "200",
                        msg = "Delete Succeed."
                    };
                }
                else
                {
                    return new GetOrderListOutput()
                    {
                        error_code = "2001",
                        status = "200",
                        msg = "Order Not Exist",
                    };
                }
            }
            return new OutputDTO()
            {
                error_code = "2000",
                status = "200",
                msg = "Delete Succeed."
            };
        }

        [HttpPost("RecoverOrderAdmin")]
        [Authorize]
        public OutputDTO RecoverOrderAdmin(AdminDeleteInput input)
        {
            var userClaim = HttpContext.User.Claims;
            var userGuid = userClaim.FirstOrDefault(c => c.Type == "UserGuid")?.Value;
            var userGroupId = userClaim.FirstOrDefault(c => c.Type == "UserGroupId")?.Value;
            if (userGroupId == "0")
            {
                return new GetOrderListOutput()
                {
                    error_code = "2002",
                    status = "200",
                    msg = "Unauthorized",
                };
            }

            if (!string.IsNullOrWhiteSpace(input.id))
            {
                var order = _dbContextHelper.OrderAllModel.Where(p => p.ORDER_ID == input.id).FirstOrDefault();
                var orderInfo = _dbContextHelper.OrderInfoModel.Where(p => p.ORDER_ID == input.id).FirstOrDefault();
                if (orderInfo != null && order != null)
                {
                    order.DELETE_DATE = null;
                    orderInfo.DELETE_DATE = null;

                    order.ORDER_STATUS_CODE = order.RECOVER_STATUS_CODE;
                    order.ORDER_STATUS_DESC = order.RECOVER_STATUS_DESC;
                    _dbContextHelper.SaveChanges();

                    return new OutputDTO()
                    {
                        error_code = "2000",
                        status = "200",
                        msg = "Recover Succeed."
                    };
                }
                else
                {
                    return new GetOrderListOutput()
                    {
                        error_code = "2001",
                        status = "200",
                        msg = "Order Not Exist",
                    };
                }
            }
            return new OutputDTO()
            {
                error_code = "2000",
                status = "200",
                msg = "Recover Succeed."
            };
        }

        [HttpPost("RecoverUserAdmin")]
        [Authorize]
        public OutputDTO RecoverUserAdmin(AdminDeleteInput input)
        {
            var userClaim = HttpContext.User.Claims;
            var userGuid = userClaim.FirstOrDefault(c => c.Type == "UserGuid")?.Value;
            var userGroupId = userClaim.FirstOrDefault(c => c.Type == "UserGroupId")?.Value;
            if (userGroupId == "0")
            {
                return new GetOrderListOutput()
                {
                    error_code = "2002",
                    status = "200",
                    msg = "Unauthorized",
                };
            }

            if (!string.IsNullOrWhiteSpace(input.id))
            {
                var user = _dbContextHelper.Users.Where(p => p.USER_ID == input.id).FirstOrDefault();
                var userInfo = _dbContextHelper.UserInfo.Where(p => p.USER_ID == input.id).FirstOrDefault();
                if (userInfo != null && user != null)
                {
                    user.DELETE_DATE = null;
                    userInfo.DELETE_DATE = null;

                    _dbContextHelper.SaveChanges();

                    return new OutputDTO()
                    {
                        error_code = "2000",
                        status = "200",
                        msg = "Recover Succeed."
                    };
                }
                else
                {
                    return new GetOrderListOutput()
                    {
                        error_code = "2001",
                        status = "200",
                        msg = "User Not Exist",
                    };
                }
            }

            return new OutputDTO()
            {
                error_code = "2000",
                status = "200",
                msg = "Recover Succeed."
            };
        }

        [HttpPost("RecoverProductAdmin")]
        [Authorize]
        public OutputDTO RecoverProductAdmin(AdminDeleteInput input)
        {
            var userClaim = HttpContext.User.Claims;
            var userGuid = userClaim.FirstOrDefault(c => c.Type == "UserGuid")?.Value;
            var userGroupId = userClaim.FirstOrDefault(c => c.Type == "UserGroupId")?.Value;
            if (userGroupId == "0")
            {
                return new GetOrderListOutput()
                {
                    error_code = "2002",
                    status = "200",
                    msg = "Unauthorized",
                };
            }

            if (!string.IsNullOrWhiteSpace(input.id))
            {
                int productId = int.Parse(input.id);
                var product = _dbContextHelper.Product.Where(p => p.PRODUCT_ID == productId).FirstOrDefault();
                var productInfo = _dbContextHelper.ProductInfo.Where(p => p.PRODUCT_ID == productId).FirstOrDefault();
                var productDetail = _dbContextHelper.ProductDetail.Where(p => p.PRODUCT_ID == productId).ToList();

                if (productInfo != null && product != null)
                {
                    product.DELETE_DATE = null ;
                    productInfo.DELETE_DATE = null;
                    foreach (var detail in productDetail)
                    {
                        detail.DELETE_DATE = null;
                    }
                    _dbContextHelper.SaveChanges();

                    return new OutputDTO()
                    {
                        error_code = "2000",
                        status = "200",
                        msg = "Recover Succeed."
                    };
                }
                else
                {
                    return new GetOrderListOutput()
                    {
                        error_code = "2001",
                        status = "200",
                        msg = "Product Not Exist",
                    };
                }
            }
            return new OutputDTO()
            {
                error_code = "2000",
                status = "200",
                msg = "Recover Succeed."
            };
        }

        [HttpPost("UploadImageAdmin")]
        [Authorize]
        public OutputDTO UploadImageAdmin(AdminProductImgUploadInput input)
        {
            int productId = int.Parse(input.product_id);
            if (string.IsNullOrWhiteSpace(input.product_id.ToString()))
            {
                return new OutputDTO()
                {
                    error_code = "2001",
                    status = "200",
                    msg = "Product Can Not Be Null."
                };
            }
            var product = _dbContextHelper.ProductInfo.Where(p => p.PRODUCT_ID == productId).FirstOrDefault();
            string imagePath1 = null;
            string imagePath2 = null;
            string imagePath3 = null;

            bool img1Set = false;
            bool img2Set = false;
            bool img3Set = false;

            if (product == null)
            {
                return new OutputDTO()
                {
                    error_code = "2001",
                    status = "200",
                    msg = "Product Not Exist."
                };
            }
            if (!string.IsNullOrWhiteSpace(input.product_media1) && !string.IsNullOrWhiteSpace(input.product_media1_base64))
            {
                _fileHelper.DownloadImageByBase64(input.product_media1_base64, "product_media1_" + input.product_id, "./FileServer/public/products");
                imagePath1 = "products/" + "product_media1_" + input.product_id + ".png";
            }
            if (!string.IsNullOrWhiteSpace(input.product_media2) && !string.IsNullOrWhiteSpace(input.product_media2_base64))
            {
                _fileHelper.DownloadImageByBase64(input.product_media2_base64, "product_media2_" + input.product_id, "./FileServer/public/products");
                imagePath2 = "products/" + "product_media2_" + input.product_id + ".png";
            }
            if (!string.IsNullOrWhiteSpace(input.product_media3) && !string.IsNullOrWhiteSpace(input.product_media3_base64))
            {
                _fileHelper.DownloadImageByBase64(input.product_media3_base64, "product_media3_" + input.product_id, "./FileServer/public/products");
                imagePath3 = "products/" + "product_media3_" + input.product_id + ".png";
            }

            if (imagePath1 != null)
            {
                if (product.PRODUCT_MEDIA1 != input.product_media1 && product.PRODUCT_MEDIA1 != input.product_media2 && product.PRODUCT_MEDIA1 != input.product_media3 && !img1Set)
                {
                    product.PRODUCT_MEDIA1 = imagePath1;
                    img1Set = true;
                }
                else if (product.PRODUCT_MEDIA2 != input.product_media1 && product.PRODUCT_MEDIA2 != input.product_media2 && product.PRODUCT_MEDIA2 != input.product_media3 && !img2Set)
                {
                    product.PRODUCT_MEDIA2 = imagePath1;
                    img2Set = true;
                }
                else if (product.PRODUCT_MEDIA3 != input.product_media1 && product.PRODUCT_MEDIA3 != input.product_media2 && product.PRODUCT_MEDIA3 != input.product_media3 && !img3Set)
                {
                    product.PRODUCT_MEDIA3 = imagePath1;
                    img3Set = true;
                }
            }
            if (imagePath2 != null)
            {
                if (product.PRODUCT_MEDIA1 != input.product_media1 && product.PRODUCT_MEDIA1 != input.product_media2 && product.PRODUCT_MEDIA1 != input.product_media3 && !img1Set)
                {
                    product.PRODUCT_MEDIA1 = imagePath2;
                    img1Set = true;
                }
                else if (product.PRODUCT_MEDIA2 != input.product_media1 && product.PRODUCT_MEDIA2 != input.product_media2 && product.PRODUCT_MEDIA2 != input.product_media3 && !img2Set)
                {
                    product.PRODUCT_MEDIA2 = imagePath2;
                    img2Set = true;
                }
                else if (product.PRODUCT_MEDIA3 != input.product_media1 && product.PRODUCT_MEDIA3 != input.product_media2 && product.PRODUCT_MEDIA3 != input.product_media3 && !img3Set)
                {
                    product.PRODUCT_MEDIA3 = imagePath2;
                    img3Set = true;
                }
            }
            if (imagePath3 != null)
            {
                if (product.PRODUCT_MEDIA1 != input.product_media1 && product.PRODUCT_MEDIA1 != input.product_media2 && product.PRODUCT_MEDIA1 != input.product_media3 && !img1Set)
                {
                    product.PRODUCT_MEDIA1 = imagePath3;
                    img1Set = true;
                }
                else if (product.PRODUCT_MEDIA2 != input.product_media1 && product.PRODUCT_MEDIA2 != input.product_media2 && product.PRODUCT_MEDIA2 != input.product_media3 && !img2Set)
                {
                    product.PRODUCT_MEDIA2 = imagePath3;
                    img2Set = true;
                }
                else if (product.PRODUCT_MEDIA3 != input.product_media1 && product.PRODUCT_MEDIA3 != input.product_media2 && product.PRODUCT_MEDIA3 != input.product_media3 && !img3Set)
                {
                    product.PRODUCT_MEDIA3 = imagePath3;
                    img3Set = true;
                }
            }

            _dbContextHelper.SaveChanges();
            return new OutputDTO()
            {
                error_code = "2000",
                status = "200",
                msg = "Confirm Return Succeed."
            };
        }
    }
}
